import json

import uvicorn
from fastapi import FastAPI, Request
from typing import List
from typing import NamedTuple
from generate_booklist_API import BookRecommendationSystem
from checkutils.vertify_util import checkIsValid
import time
app = FastAPI()


class AlRespdata(NamedTuple):
    status_code: int
    status_message: str

    def to_dict(self):
        return {
            'status_code': self.status_code,
            'status_message': self.status_message
        }


class thisdata(NamedTuple):
    algorithm_base_resp: AlRespdata
    record_ids: List[int]
    topic_name: str
    topic_desc: str

    def to_dict(self):
        return {
            'algorithm_base_resp': self.algorithm_base_resp.to_dict(),
            'record_ids': self.record_ids,
            'topic_name': self.topic_name,
            'topic_desc': self.topic_desc
        }
class res(NamedTuple):
    code: int
    data: thisdata
    message: str
    request_id: str
    time_elapsed: str

    def to_dict(self):
        return {
            'code': self.code,
            'data': self.data.to_dict(),
            'message': self.message,
            'request_id': self.request_id,
            'time_elapsed': self.time_elapsed
        }

app_token = '279D4B5D5F2FD5FE'
app_key = 'DF469779279D4B5D5F2FD5FE785038E5'
# ... 其他代码 ...
file_path = './configs/config.json'
# with open(file_path, 'r') as file:
#     data_config = json.load(file)

recommendation_system = BookRecommendationSystem(file_path)

def error_res(txt):
    al_resp = AlRespdata(status_code=1, status_message='error')
    data = thisdata(al_resp, None, None, None)
    result = res(10001, data, txt, None, None)
    # 调用 to_dict 方法来转换为字典
    result_dict = result.to_dict()

    # 返回字典
    return result_dict

@app.post('/api/rec/bookrec/v1')
async def test(request: Request):
    
    json_data = await request.json()
    user_id = json_data['userId']
    group_code = json_data['groupCode']
    labels = json_data['labels']
    token = json_data['token']
    _time = json_data['timestamp']
    inf_enc = json_data['inf_enc']

    # ckv = checkIsValid(uid=user_id)
    # if param := ckv.check_param_exist(token, _time, inf_enc):
    #     txt=param['Response']['Error']['Message']
    #     # return error_res(txt)


    # if res_check := ckv.check_is_valid(app_token, token, _time, app_key, inf_enc):
    #     txt=res_check['Response']['Error']['Message']
    #     # return error_res(txt)
    print(user_id)
    print(group_code)
    print(labels)
    starttime=time.time()    
    recommendation = await recommendation_system.generate_book_list(user_id=int(user_id), group_code=str(group_code),
                                                              labels=labels)
    endtime=time.time()                                                          
    record_ids = recommendation.get('recordIds')
    topic_name = recommendation.get('topicName')
    topic_desc = recommendation.get('topicDesc')
    al_resp = AlRespdata(status_code=0, status_message='success')
    data = thisdata(al_resp, record_ids, topic_name, topic_desc)
    result = res(10000, data, 'success', None, (endtime-starttime))
    # 调用 to_dict 方法来转换为字典
    result_dict = result.to_dict()
    print("last time:",endtime-starttime)
    # 返回字典
    return result_dict

if __name__ == "__main__":
    uvicorn.run("gen_fastapi:app", host="0.0.0.0", port=9007, reload=False)